package com.flyu.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

// 统计网站在线人数：统计session
public class OnlineCountListener implements HttpSessionListener {
    @Override
    // 创建session便会触发
    public void sessionCreated(HttpSessionEvent se) {
        // 获得servletcontext
        ServletContext ctx = se.getSession().getServletContext();

        System.out.println(se.getSession().getId());

        Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");

        if (onlineCount==null){
            onlineCount = new Integer(1);
        }else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count++);
        }

        ctx.setAttribute("OnlineCount", onlineCount);
    }

    @Override
    // 销毁
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        se.getSession().invalidate();   // 手动销毁
        Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");

        if (onlineCount==null){
            onlineCount = new Integer(0);
        }else {
            int count = onlineCount.intValue();
            onlineCount = new Integer(count--);
        }

        ctx.setAttribute("OnlineCount", onlineCount);
    }

    /*
    session的销毁
    1. 手动
    2. 自动：<session-config>1</session-config>
     */
}
